const fs = require('fs');
const path = require('path');
const COS = require('cos-nodejs-sdk-v5');

const cos = new COS({
    SecretId: process.env.COS_SECRET_ID || 'wx4abf7dc46f46fd7b',
    SecretKey: process.env.COS_SECRET_KEY || '38553c5e31f2fab93143fb7ef865e291',
});

// 改进后的上传函数
exports.uploadFile = async (filePath) => {
    try {
        const fileName = path.basename(filePath);
        const result = await cos.putObject({
            Bucket: '7072-prod-5gduafzd5d123d73-1326429543',
            Region: 'ap-shanghai',
            Key: `images/${Date.now()}_${fileName}`, // 按日期组织目录
            StorageClass: 'STANDARD',
            Body: fs.createReadStream(filePath),
            onProgress: (progressData) => {
                console.log('上传进度:', progressData.percent * 100 + '%');
            },
        });
        
        // 返回完整的可访问URL
        return {
            success: true,
            url: `https://${result.Location}`,
            key: result.Key
        };
    } catch (err) {
        console.error('COS上传失败:', err);
        return {
            success: false,
            error: err.message
        };
    }
};

// 整合后的上传接口
exports.uploadImage = async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: '请选择要上传的文件' });
        }

        // 1. 先上传到本地
        const localPath = req.file.path;
        
        // 2. 上传到COS
        const cosResult = await this.uploadFile(localPath);
        if (!cosResult.success) {
            throw new Error(cosResult.error);
        }

        // 3. 删除本地临时文件
        fs.unlink(localPath, (err) => {
            if (err) console.error('删除临时文件失败:', err);
        });

        res.status(200).json({
            status: 200,
            message: '图片上传成功',
            data: {
                filePath: cosResult.url, // 返回完整的COS URL
                localPath: `/uploads/${req.file.filename}` // 保留本地路径参考
            }
        });
    } catch (error) {
        console.error('上传处理失败:', error);
        res.status(500).json({
            status: 500,
            message: '图片上传失败',
            error: error.message
        });
    }
};
/*const COS = require('cos-nodejs-sdk-v5');
const cos = new COS({
    SecretId: 'wx4abf7dc46f46fd7b',
    SecretKey: '38553c5e31f2fab93143fb7ef865e291',
});

// 上传文件到对象存储
exports.uploadFile = async (filePath) => {
    try {
        const result = await cos.putObject({
            Bucket: '7072-prod-5gduafzd5d123d73-1326429543',
            Region: 'ap-shanghai',
            Key: '/', // 上传到对象存储的路径
            StorageClass: 'STANDARD',
            Body: fs.createReadStream(filePath),
            onProgress: function (progressData) {
                console.log(JSON.stringify(progressData));
            },
        });
        console.log(result);
    } catch (err) {
        console.error(err);
    }
};
*/